<script setup lang="ts">
import { getAssignTreeApi } from "@/apis/user";
import { onMounted, reactive, ref } from "vue";
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import { userStore } from "@/stores/user";
import { assignApi } from "@/apis/role";
import { ElMessage, ElTree } from "element-plus";
const treeRef = ref<InstanceType<typeof ElTree>>();
const user = userStore();
const dialog = useDialog().dialog;
const assignTree = reactive({
  list: [],
  assignTreeChecked: [],
});
const parms = reactive({
  userId: "",
  roleId: "",
});
const checked = (id: string, data: any, newArr: any) => {
  data.forEach((element: any) => {
    if (element.id == id) {
      if (element.children && element.children.length == 0) {
        newArr.push(element.id);
      }
    } else {
      if (element.children && element.children.length != 0) {
        checked(id, element.children, newArr);
      }
    }
  });
};
const getAssignTree = async () => {
  let res = await getAssignTreeApi(parms);
  if (res && res.code == 200) {
    assignTree.list = res.data.listmenu;
    assignTree.assignTreeChecked = res.data.checkList;
    /*  if (assignTree.assignTreeChecked.length > 0) {
      let newArr: any = [];
      assignTree.assignTreeChecked.forEach((item: any) => {
        checked(item, assignTree.list, newArr);
      });
      assignTree.assignTreeChecked = newArr;
      console.log(newArr);
    } */
  }
};

const defaultProps = {
  children: "children",
  label: "title",
  id: "id",
};
const commitParams = reactive({
  roleId: "",
  menuIds: [] as string[],
});
const commit = async () => {
	const checkIds=treeRef.value?.getCheckedKeys() as string[]
  const halfcheckedKeys=treeRef.value?.getHalfCheckedKeys() as string[]
	let ids=checkIds?.concat(halfcheckedKeys)
  commitParams.roleId = parms.roleId;
  commitParams.menuIds = ids;
	
	let res = await assignApi(commitParams);
  if (res && res.code == 200) {
    ElMessage.success(res.msg);
    dialog.visible = false;
  }
};

const show = async (roleId: string, name: string) => {
  assignTree.assignTreeChecked = [];
  assignTree.list = [];
  dialog.title = "分配角色";
  dialog.visible = true;
  parms.roleId = roleId;
  parms.userId = user.getUserId;
  await getAssignTree();
};
defineExpose({
  show,
});
</script>

<template>
  <SysDialog
    :title="dialog.title"
    :visible="dialog.visible"
    :width="dialog.width"
    :height="dialog.height"
    @onClose="dialog.visible = false"
    @onConfirm="commit"
  >
    <template v-slot:content>
      <el-tree
        ref="treeRef"
        :data="assignTree.list"
        :props="defaultProps"
        :default-checked-keys="assignTree.assignTreeChecked"
        node-key="id"
        :check-strictly="true"
        default-expand-all
        show-checkbox
      ></el-tree>
    </template>
  </SysDialog>
</template>

<style scoped></style>
